package com.student_exam_system.controller;

import com.alibaba.fastjson.JSON;
import com.student_exam_system.Util.SimpleCache;
import com.student_exam_system.pojo.LoginUser;
import com.student_exam_system.pojo.Result;
import com.student_exam_system.pojo.User;
import com.student_exam_system.service.UserService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;



/**
 * @author fire'ge
 */
@Controller
public class UserController {
    private final UserService userService;

    public UserController(@Qualifier("userServiceImpl") UserService userService) {
        this.userService = userService;
    }


    @ResponseBody
    @RequestMapping(value = "/user/login/{phoneNum}/{pwd}",produces = "application/json;charset=utf-8")
    public String login(@PathVariable String phoneNum,
                     @PathVariable String pwd) {
        User user = new User();
        user.setUserPassword(pwd);
        user.setUserPhoneNum(phoneNum);
        Result login = userService.login(user);
        return JSON.toJSONString(login);
    }
    @ResponseBody
    @RequestMapping(value = "/user/logout",produces = "application/json;charset=utf-8")
    public String logout() {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authenticationToken.getPrincipal();
        SimpleCache cache = SimpleCache.getInstance();
        cache.remove("login"+principal.getUser().getUserId());
        return JSON.toJSONString(Result.succ(200,"注销成功",null));
    }
    @ResponseBody
    @RequestMapping("/register/{userPhoneNum}/{userPassword}/{classId}/{userIdentity}")
    public int registerStudent(@PathVariable String userPhoneNum, @PathVariable String userPassword, @PathVariable int classId, @PathVariable String userIdentity){
        return userService.addUser(new User(0,userPhoneNum,userPassword,userIdentity,classId));
    }




}
